// ============ 全局配置 ============
const API_URL = '/api/rest/role'; // 角色接口URL
let gridInstance = null;
const roleModal = new bootstrap.Modal(document.getElementById('roleModal'));
const roleForm = document.getElementById('role-form');
const roleModalLabel = document.getElementById('roleModalLabel');
const alertMessage = document.getElementById('alertMessage');

// 内置角色类型（不允许删除/修改类型）
const BUILT_IN_ROLES = ['系统管理员', '部门经理', '业务员'];

// ============ 页面加载初始化 ============
document.addEventListener('DOMContentLoaded', () => {
  // 登录状态校验（复用utils.js）
  loginCheck();
  // 初始化表格
  initGrid();
  // 绑定表单提交事件
  bindFormSubmit();
  // 绑定搜索表单事件
  bindSearchForm();
  // 绑定模态框关闭事件（重置表单）
  bindModalClose();
});

// ============ Grid表格初始化 ============
function initGrid() {
  const columns = [
    { name: 'ID', id: 'id', width: '8%' },
    { name: '角色名称', id: 'name', sort: true },
    { name: '角色类型', id: 'type', sort: true },
    { name: '数据范围', id: 'dataScope', sort: true },
    { 
      name: '创建时间', 
      id: 'createAt', 
      sort: true,
      formatter: (value) => value ? new Date(value).toLocaleString() : '-'
    },
    {
      name: '操作',
      id: 'actions',
      width: '20%',
      formatter: (_, row) => {
        const id = row.cells[0].data;
        const roleType = row.cells[2].data;
        const isBuiltIn = BUILT_IN_ROLES.includes(roleType);

        // 操作按钮：内置角色隐藏删除按钮
        return gridjs.html(`
          <button type="button" class="btn btn-sm btn-outline-primary m-1" onclick="openEditModal('${id}')">
            <i class="fas fa-edit"></i> 编辑
          </button>
          ${!isBuiltIn ? `
            <button type="button" class="btn btn-sm btn-outline-danger m-1" onclick="deleteRole('${id}', '${row.cells[1].data}')">
              <i class="fas fa-trash"></i> 删除
            </button>
          ` : ''}
        `);
      }
    }
  ];

  const gridOptions = {
    columns,
    server: {
      url: API_URL,
      then: (data) => {
        // 格式化表格数据
        return data.content.map(role => [
          role.id,
          role.name,
          role.type,
          role.dataScope,
          role.createAt
        ]);
      },
      total: (data) => data.totalElements,
      loading: {
        html: () => gridjs.html('<div class="text-center py-4"><i class="fas fa-spinner fa-spin me-2"></i> 加载角色数据中...</div>')
      }
    },
    pagination: {
      limit: 10, // 每页10条
      server: {
        url: (prev, page, limit) => addQueryParam(prev, `page=${page - 1}&size=${limit}`)
      }
    },
    search: false,
    sort: true,
    language: {
      pagination: {
        previous: '上一页',
        next: '下一页',
        showing: '显示第',
        of: '条，共',
        to: '至',
        results: '条记录'
      },
      noRecordsFound: '暂无角色数据'
    }
  };

  // 销毁旧实例，重建表格
  if (gridInstance) gridInstance.destroy();
  gridInstance = new gridjs.Grid(gridOptions).render(document.getElementById('gridjs-container'));
}

// ============ 新增角色模态框 ============
function openAddModal() {
  // 重置表单
  roleForm.reset();
  roleForm.classList.remove('was-validated');
  alertMessage.innerHTML = '';
  // 启用类型选择（新增时可选择所有类型）
  roleForm.querySelector('[name="type"]').disabled = false;
  // 设置模态框标题
  roleModalLabel.textContent = '新增角色';
  // 清空隐藏ID字段
  roleForm.querySelector('[name="id"]').value = '';
  // 打开模态框
  roleModal.show();
}

// ============ 编辑角色模态框 ============
function openEditModal(id) {
  // 重置表单状态
  roleForm.reset();
  roleForm.classList.remove('was-validated');
  alertMessage.innerHTML = '';

  // 获取角色详情
  fetch(`${API_URL}/${id}`)
    .then(res => {
      if (!res.ok) throw new Error('获取角色详情失败');
      return res.json();
    })
    .then(role => {
      // 填充表单数据
      roleForm.querySelector('[name="id"]').value = role.id;
      roleForm.querySelector('[name="name"]').value = role.name;
      roleForm.querySelector('[name="type"]').value = role.type;
      roleForm.querySelector('[name="dataScope"]').value = role.dataScope;

      // 内置角色禁用类型选择
      const typeSelect = roleForm.querySelector('[name="type"]');
      typeSelect.disabled = BUILT_IN_ROLES.includes(role.type);

      // 设置模态框标题
      roleModalLabel.textContent = '编辑角色';
      // 打开模态框
      roleModal.show();
    })
    .catch(error => {
      showToast(error.message, 'error');
    });
}

// ============ 表单提交（新增/编辑） ============
function bindFormSubmit() {
  roleForm.addEventListener('submit', (e) => {
    e.preventDefault();

    // 表单验证：必填项校验
    if (!roleForm.checkValidity()) {
      roleForm.classList.add('was-validated');
      return;
    }

    const isEdit = !!roleForm.querySelector('[name="id"]').value;
    const formData = formToJson(roleForm);
    const config = {
      method: isEdit ? 'PATCH' : 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData)
    };

    // 编辑时拼接ID
    const url = isEdit ? `${API_URL}/${formData.id}` : API_URL;

    fetch(url, config)
      .then(res => {
        if (!res.ok) {
          return res.json().then(err => {
            throw new Error(err.message || (isEdit ? '编辑角色失败' : '新增角色失败'));
          });
        }
        return res.json();
      })
      .then(() => {
        // 操作成功
        roleModal.hide();
        showToast(isEdit ? '编辑角色成功' : '新增角色成功');
        initGrid(); // 刷新表格
      })
      .catch(error => {
        // 显示错误信息
        alertMessage.innerHTML = `<div class="alert alert-danger">${error.message}</div>`;
        showToast(error.message, 'error');
      });
  });
}

// ============ 删除角色（二次确认） ============
function deleteRole(id, roleName) {
  // 二次确认
  if (!confirm(`确定要删除角色「${roleName}」吗？删除后不可恢复！`)) {
    return;
  }

  fetch(`${API_URL}/${id}`, { method: 'DELETE' })
    .then(res => {
      if (!res.ok) {
        return res.json().then(err => {
          throw new Error(err.message || '删除角色失败');
        });
      }
      return res.json();
    })
    .then(() => {
      showToast('删除角色成功');
      initGrid(); // 刷新表格
    })
    .catch(error => {
      showToast(error.message, 'error');
    });
}

// ============ 搜索表单绑定 ============
function bindSearchForm() {
  const searchForm = document.getElementById('search-form');
  searchForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const formData = new FormData(searchForm);
    const params = new URLSearchParams(formData).toString();
    // 更新表格请求URL
    gridInstance.updateConfig({
      server: { ...gridInstance.config.server, url: addQueryParam(API_URL, params) }
    }).forceRender();
  });

  // 重置按钮：清空搜索条件
  searchForm.querySelector('[type="reset"]').addEventListener('click', () => {
    setTimeout(() => {
      gridInstance.updateConfig({
        server: { ...gridInstance.config.server, url: API_URL }
      }).forceRender();
    }, 100);
  });
}

// ============ 模态框关闭事件（重置表单） ============
function bindModalClose() {
  document.getElementById('roleModal').addEventListener('hidden.bs.modal', () => {
    roleForm.reset();
    roleForm.classList.remove('was-validated');
    alertMessage.innerHTML = '';
    roleForm.querySelector('[name="type"]').disabled = false; // 重置类型选择禁用状态
  });
}

// ============ 暴露全局函数 ============
window.initGrid = initGrid;
window.openAddModal = openAddModal;
window.openEditModal = openEditModal;
window.deleteRole = deleteRole;